package cn.uyunsky.platform.service.impl;

import cn.uyunsky.platform.data.GridPageVO;
import cn.uyunsky.platform.data.JsonTool;
import cn.uyunsky.platform.data.UData;
import cn.uyunsky.platform.data.UDataTool;
import cn.uyunsky.platform.entity.impl.PlRole;
import cn.uyunsky.platform.exception.PLException;
import cn.uyunsky.platform.jdbc.page.Page;
import cn.uyunsky.platform.jdbc.page.PageRequest;
import cn.uyunsky.platform.jdbc.page.PageRequestFactory;
import cn.uyunsky.platform.service.IServiceAbstract;
import cn.uyunsky.platform.util.PL;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色维护服务
 */
@Service(value = "PLRoleService")
@Transactional
public class PLRoleService extends IServiceAbstract {
    private static class OPTYPE {
        public static final String ADD = "ADD";
        public static final String UPD = "UPD";
        public static final String DEL = "DEL";
        public static final String GET = "GET";//根据rowid获取记录
        public static final String SEARCH = "SEARCH";
    }


    private HibernateTemplate hibernateTemplate;

    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }

    @Override
    public UData doService(UData data) throws PLException {
        String optype = (String) data.getBody().get("optype");
        String pluserid = null;
        if (OPTYPE.ADD.equals(optype)) {
            pluserid = this.addRole(data);
        } else if (OPTYPE.UPD.equals(optype)) {
            pluserid = this.updateRole(data);
        } else if (OPTYPE.DEL.equals(optype)) {
            pluserid = this.deleteRole(data);
        } else if (OPTYPE.GET.equals(optype)) {
            return this.getRole(data);
        } else if (OPTYPE.SEARCH.equals(optype)) {
            return this.searchRole(data);
        } else {
            throw new PLException("9999");
        }

        return UDataTool.createOneUData("id", pluserid);
    }


    private UData getRole(UData data) {

        final String roleId = (String) data.getBody().get("id");
        PlRole role = hibernateTemplate.load(PlRole.class, roleId);

        //PlRole 单值域
        Map roleTmp = new HashMap();
        roleTmp.put("id", role.getId());
        roleTmp.put("createDate", role.getCreateDate());
        roleTmp.put("flag", role.getFlag());
        roleTmp.put("roleDes", role.getRoleDes());

        return UDataTool.createSuccessResult(roleTmp);
    }

    private String deleteRole(UData data) {
        final String roleId = (String) data.getBody().get("id");
        PlRole role = hibernateTemplate.load(PlRole.class, roleId);
        hibernateTemplate.delete(role);
        return roleId;
    }

    private String updateRole(UData data) {
        PlRole plRoleReq = PL.JSON.fromJSON(data.getJson(), PlRole.class);

        PlRole role = hibernateTemplate.load(PlRole.class, plRoleReq.getId());
//        role.setCreateDate(new Timestamp(System.currentTimeMillis()));
        role.setFlag("0");
        role.setRoleDes(plRoleReq.getRoleDes());
        hibernateTemplate.save(role);

        return plRoleReq.getId();
    }

    private String addRole(UData data) {

        PlRole plRole = PL.JSON.fromJSON(data.getJson(), PlRole.class);
        plRole.setCreateDate(new Timestamp(System.currentTimeMillis()));
        plRole.setFlag("0");//不提供管理员角色的增加
        hibernateTemplate.save(plRole);
        return plRole.getId();
    }


    /**
     * @param data {
     *             parameter 角色名
     *             }
     * @return
     */
    private UData searchRole(UData data) {
         /*======================另一种方式=========================*/
        final String hql2 =
                "select t.id, t.roleDes, t.createDate, t.flag" +
                        " from PlRole t" +
                        " where t.roleDes like CONCAT('%', :parameter, '%')";

        PageRequest pageRequest = PageRequestFactory.bindPageRequest(new PLRolePageRequest(), data.getBody());
        Page pageRes = PL.hibernateTemplateHelper.pageQuery(hql2, pageRequest);
        List result = pageRes.getResult();
        List newresult = new ArrayList();
        for (int i = 0; i < result.size(); i++) {
            Object[] oa = (Object[]) result.get(i);
            Map r = new HashMap();
            r.put("id", oa[0]);
            r.put("roleDes", oa[1]);
            r.put("createDate", oa[2]);
            r.put("flag", oa[3]);
            newresult.add(r);
        }

        GridPageVO vo = new GridPageVO(pageRes.getTotalCount(), newresult);
        logger.debug("vo json:" + JsonTool.toJSON(vo));

        return UDataTool.createOneUData("grid", vo);
    }

    public static class PLRolePageRequest extends PageRequest {

        private String parameter;

        public String getParameter() {
            return parameter;
        }

        public void setParameter(String parameter) {
            this.parameter = parameter;
        }
    }
}
